﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GoodMan.Tool.Framework;
using GoodMan.Infrastructure.Entities.Entity;
using GoodMan.Portal.WebLogic;
using GoodMan.Infrastructure.Entities.Enum;
using GoodMan.Portal.Biz;
using GoodMan.Portal.Web.Areas.WorkSpace.Models;
using GoodMan.Tool.Framework;
using System.Linq.Expressions;
using GoodMan.Infrastructure.Entities.Contract;

namespace GoodMan.Portal.Web.Areas.WorkSpace.Controllers
{
    /// <summary>
    /// 学校校级管理员
    /// </summary>
    [ErrorHandle]
    [Warp]
    [Auth(UserRole.CollegeAdmin)]
    public class CollegeAdminController : Controller
    {
        //
        // GET: /WorkSpace/CollegeAdmin/

        public ActionResult Index()
        {
            return View();
        }

        #region 信息发布平台
        public ActionResult InfoPublish(int page = 0)
        {
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SavePublishInfo(PublishInfoModel pubInfoModel)
        {
            var pubinfo = new Information()
            {
                Id = pubInfoModel.Id,
                Category = pubInfoModel.Category,
                CTR = 0,
                EmailAdress = pubInfoModel.EmailAdress,
                ExpireDate = pubInfoModel.ExpireDate,
                JobDescrption = pubInfoModel.JobDescrption,
                LinkMan = pubInfoModel.LinkMan,
                Phone = pubInfoModel.Phone,
                PubDate = System.DateTime.Now,
                RecruitDep = pubInfoModel.RecruitDep,
                RecruitNum = pubInfoModel.RecruitNum,
                SexReq = pubInfoModel.SexReq,
                SalaryLevel = pubInfoModel.SalaryLevel,
                Title = pubInfoModel.Title,
                WorkArea = pubInfoModel.WorkArea + "-" + pubInfoModel.DisCenter
            };
            ViewBag.isSuccess = CollegeBiz.SavePublishInfo(pubinfo);

            return Redirect("/WorkSpace/CollegeAdmin/InfoList");
        }

        public ActionResult DeletePubInfo(int id = 0, int page = 0)
        {
            ViewBag.isSuccess = CollegeBiz.DeletePubInfoByID(id);
            return Redirect("/WorkSpace/CollegeAdmin/InfoList?page=" + page);
        }

        /// <summary>
        /// 编辑/修改发布信息
        /// </summary>
        /// <returns></returns>
        public ActionResult InfoModify(string id, int page = 0)
        {
            ViewBag.page = page;
            ViewBag.SpecPubInfo = new Information().Find(id);
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult ModifyPubInfo(PublishInfoModel pubinfomodel, int page = 0)
        {
            var tempinfo = new Information().Find(pubinfomodel.Id.ToString());
            if (tempinfo != null)
            {
                tempinfo.JobDescrption = pubinfomodel.JobDescrption;
                tempinfo.LinkMan = pubinfomodel.LinkMan;
                tempinfo.Phone = pubinfomodel.Phone;
                tempinfo.PubDate = System.DateTime.Now;
                tempinfo.RecruitDep = pubinfomodel.RecruitDep;
                tempinfo.RecruitNum = pubinfomodel.RecruitNum;
                tempinfo.SalaryLevel = pubinfomodel.SalaryLevel;
                tempinfo.SexReq = pubinfomodel.SexReq;
                tempinfo.Title = pubinfomodel.Title;
                tempinfo.WorkArea = pubinfomodel.WorkArea + "-" + pubinfomodel.DisCenter;
                tempinfo.Category = pubinfomodel.Category;
                tempinfo.EmailAdress = pubinfomodel.EmailAdress;
                tempinfo.ExpireDate = pubinfomodel.ExpireDate;

                ViewBag.isSuccess = CollegeBiz.ModifyPubInfoById(tempinfo);
            }
            return Redirect("/WorkSpace/CollegeAdmin/InfoList?page=" + page);
        }

        public ActionResult InfoList(int page = 0, int oper = 0)
        {
            var pubinfoList = CollegeBiz.GetAllPubInfo(oper, page, 10);
            ViewBag.PubInfo = pubinfoList;
            return View();
        }

        #endregion

        #region 信息发布平台
        /// <summary>
        /// 发布公告
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult NoticePublish()
        {
            return View();
        }
        /// <summary>
        /// 发布公告
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult NoticePublish(NoticeModel model)
        {
            if (!NoticeBiz.IsExits(model.Title))
            {
                ViewBag.Error = "标题已存在！";
                return View();
            }

            var pubNotice = new Notice()
            {
                Promulgator = HttpContext.User.Identity.Name,
                Content = model.Content,
                CreateTime = DateTime.Now,
                Title = model.Title,
                SubTitle = model.SubTitle
            };
            if (pubNotice.PostAdd() == null)
            {
                LogHelper.Write(CommonLogger.UserSystem, LogLevel.Error, String.Format("校级管理员：{0}添加公告。数据为：{1}",
                   pubNotice.Title, pubNotice.ToJson()));
                ViewBag.Error = "添加公告信息失败！";
            }
            ViewBag.Error = "";

            return View();
        }
        /// <summary>
        /// 删除公告
        /// </summary>
        /// <param name="id"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult Delete(int id = 0, int page = 0)
        {
            var notice = new Notice().Find(id.ToString());

            if (notice != null)
            {

                if (notice.PostDelete() == null)
                {
                    LogHelper.Write(CommonLogger.UserSystem, LogLevel.Error, String.Format("校级管理员：{0}删除公告。数据为：{1}",
                     notice.Title, notice.ToJson()));
                    ViewBag.Error = "删除公告信息失败！";
                    return View();
                }
            }
            ViewBag.Error = "";
            return Redirect("/WorkSpace/CollegeAdmin/NoticeList?page=" + page);
        }

        /// <summary>
        /// 编辑/修改发布信息
        /// </summary>
        /// <returns></returns>
        public ActionResult NoticeModify(string id, int page = 0)
        {
            ViewBag.page = page;
            ViewBag.NoticeModel = new Notice().Find(id);
            return View();
        }
        /// <summary>
        /// 修改公告
        /// </summary>
        /// <param name="model"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult NoticeModify(NoticeModel model, int page = 0)
        {
            var tempNotice = new Notice().Find(model.Id.ToString());
            if (tempNotice != null)
            {
                tempNotice.Content = model.Content;
                tempNotice.Title = model.Title;
                tempNotice.SubTitle = model.SubTitle;
                tempNotice.Promulgator = HttpContext.User.Identity.Name;

                if (tempNotice.PostModify() == null)
                {
                    LogHelper.Write(CommonLogger.UserSystem, LogLevel.Error, String.Format("校级管理员：{0}修改公告。数据为：{1}",
                   tempNotice.Title, tempNotice.ToJson()));
                    ViewBag.Error = "修改公告信息失败！";
                    return View();
                }
                ViewBag.Error = "";
            }
            return Redirect("/WorkSpace/CollegeAdmin/NoticeList?page=" + page);
        }
        /// <summary>
        /// 公告列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="search"></param>
        /// <returns></returns>
        public ActionResult NoticeList(int page = 0, string searchKey = "")
        {
            var NoticeList = NoticeBiz.GetAllNotices(page, 10, searchKey);
            ViewBag.NoticeList = NoticeList;
            ViewBag.Search = searchKey;
            return View();
        }

        /// <summary>
        /// 公告详情
        /// </summary>
        /// <param name="id"></param>
        /// <param name="page"></param>
        /// <param name="r"></param>
        /// <returns></returns>
        public ActionResult NoticeInfo(int id, int page = 0, int r = 0)
        {
            ViewBag.page = page;
            ViewBag.NoticeModel = new Notice().Find(id.ToString());
            return View();
        }
        /// <summary>
        /// 公告标题是否存在
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool NoticeNameOnly(string name)
        {
            return NoticeBiz.IsExits(name);
        }
        #endregion

        #region 商品分类
        public ActionResult ProductCategory()
        {
           ViewBag.Categorys=ProductCategoryBiz.GetAllProductCategory();
            return View();
        }

        public ActionResult ProductCategoryDetail(int id=0)
        {
            ViewBag.ParentCategorys = ProductCategoryBiz.GetProductCategorysByLevel();
            if (id == -1)
            {
                ViewBag.isSuccess = true;
            }
            else if (id == -2)
            {
                ViewBag.isSuccess = false;
            }
            if (id > 0)
            {
                ViewBag.Category = ProductCategoryBiz.GetProductCategoryById(id);
            }
            return View();
        }
        [HttpPost]
        public ActionResult SaveProductCategory(int productCategoryId, string categoryName, int parentID)
        {
            var isSuccess = ProductCategoryBiz.SaveProductCategory(productCategoryId,categoryName, parentID, true);
            int opId = -1;
            if (!isSuccess)
            {
                opId = -2;
            }

            return Redirect("/WorkSpace/CollegeAdmin/ProductCategoryDetail/" + opId);
        }
        public ActionResult DeleteProductCategory(int productCategoryId = 0)
        {
            ViewBag.isSuccess = ProductCategoryBiz.DeleteProductCategory(productCategoryId);
            return Redirect("/WorkSpace/CollegeAdmin/ProductCategory");
        }
        public ActionResult ChangeCategoryState(int productCategoryId = 0)
        {
            ViewBag.isSuccess = ProductCategoryBiz.ChangeCategoryState(productCategoryId);
            return Redirect("/WorkSpace/CollegeAdmin/ProductCategory");
        }
        public bool IsExitsCategory(string categoryName)
        {
            return DormitoryBiz.IsExits(categoryName);
        }
        #endregion

        #region 普通商品
        public ActionResult GeneralProducts(string productkey="",int page = 0,int categoryId=0,int subcategoryId=0)
        {
            //商品分类
            ItemListBox<ProductCategory> categorys = ProductCategoryBiz.GetAllProductCategory();
            List<Object> objList = null;
            if (categorys != null && categorys.Data != null && categorys.Data.Any())
            {
                objList = new List<object>();
                List<object> subList = new List<object>();
                subList.Add(new { value = 0, name = "请选择" });
                objList.Add(new { value = 0, name = "请选择", children = subList});
                foreach (var item in categorys.Data)
                {
                    subList = null;
                    if (item.productCategorys != null && item.productCategorys.Any())
                    {
                        subList = new List<object>();
                        subList.Add(new { value = 0, name = "请选择" });
                        foreach (var subItem in item.productCategorys)
                        {
                            subList.Add(new { value = subItem.Id, name = subItem.CategoryName });
                        }
                    }
                    if (subList != null)
                    {
                        objList.Add(new { value = item.Id, name = item.CategoryName, children = subList });
                    }
                    else
                    {
                        subList = new List<object>();
                        subList.Add(new { value = 0, name = "请选择" });
                        objList.Add(new { value = item.Id, name = item.CategoryName,children = subList });
                    }
                }
            }
            ViewBag.CategorysList = objList.ToJson();
            ViewBag.Data = ProductBiz.GetAllProductsByType(productkey, 1, categoryId, subcategoryId, page, 10);
            ViewBag.SearchKey = productkey;
            ViewBag.CategoryID = categoryId;
            ViewBag.SubCategoryID = subcategoryId;
            return View();
        }
        [HttpPost]
        public ActionResult SearchProducts(string productKey = "", int productType = 0, int productSubType = 0)
        {
            return Redirect("/WorkSpace/CollegeAdmin/GeneralProducts?productkey=" + productKey + "&categoryId=" + productType + "&subcategoryId=" + productSubType);
        }

        public ActionResult GeneralProductsDetail(int id = 0)
        {
            //商品楼栋
            ViewBag.Dormitorys = SupportBiz.GetDormitories();
            ItemListBox<ProductCategory> categorys = ProductCategoryBiz.GetAllProductCategory();
          //商品分类
            List<Object> objList= null;
            if (categorys != null && categorys.Data != null && categorys.Data.Any())
            {
                objList = new List<object>();
                foreach (var item in categorys.Data)
                {
                    List<object> subList = null;
                    if(item.productCategorys!=null&&item.productCategorys.Any())
                    {
                        subList = new List<object>();
                        foreach (var subItem in item.productCategorys)
                        {
                            subList.Add(new { value = subItem.Id, name = subItem.CategoryName });
                        }
                    }
                    if (subList != null)
                    {
                        objList.Add(new { value = item.Id, name = item.CategoryName, children = subList });
                    }
                    else
                    {
                        objList.Add(new { value = item.Id, name = item.CategoryName});
                    }
                }
            }

            ViewBag.CategorysList = objList.ToJson();
            //消息
            if (id == -1)
            {
                ViewBag.isSuccess = true;
            }
            else if (id == -2)
            {
                ViewBag.isSuccess = false;
            }
            //编辑时获取商品信息
            if (id > 0)
            {
                ViewBag.productiId = id;
                ViewBag.product = new Product().Find(id.ToString());
                ViewBag.policy = new Policy().Find(c => c.ProductId == id && c.PolicyType == 1);
                ViewBag.productRepertorys = new ProductRepertory().FindAll(c => c.ProductId == id);//ProductRepertoryBiz.GetProductRepertoryByProductId(id);
            }
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SaveGeneralProducts(ProductModel productModel,string dormitoryIDs)
        { 
             var username = System.Web.HttpContext.Current.User.Identity.Name;
            // var user = new User().Find(username);
            //商品信息
            var product = new Product() 
            { 
                AreaCode=AreaCode.Normal,
                BusinessId=0,
                CapsPeople=0,
                Catering="",
                CreateDate=DateTime.Now,
                Description = productModel.Description,
                Id=productModel.Id,
                Images=productModel.Images,
                ProductCode=productModel.ProductCode,
                ProductName=productModel.ProductName,
                ProductSubType=productModel.ProductSubType,
                ProductType=productModel.ProductType,
                PurchasePrice=productModel.PurchasePrice,
                OriginalPrice =0,
                Value=5
            };
            //处理产品规格
            string versionStr = "";
            if (productModel.VerName != null && productModel.VerName.Length > 0)
            {
                for (int i = 0; i < productModel.VerName.Length; i++)
                {
                    if (productModel.VerName[i] != "" && productModel.VerValue[i] != "")
                    {
                        versionStr = versionStr + productModel.VerName[i] + "#" + (productModel.VerValue[i] == "" ? productModel.VerName[i] : productModel.VerValue[i]) + ";";
                    }
                }
            }
            if (versionStr != "" && versionStr.Length > 0)
            {
                versionStr = versionStr.Substring(0, versionStr.Length - 1);
            }
            product.Version = versionStr;
            //商品价格策略信息
            var policy = new Policy()
            {
                Id=productModel.PolicyId,
                CreateDate=DateTime.Now,
                Creator = username,// user.RealName,
                PolicyType=1,
                Price=productModel.SalePrice,
                ProductName=productModel.ProductName,
                StartDate=DateTime.Now,
                ExpireDate=DateTime.Now,
                IsActive=true
            };
            List<ProductRepertory> repertoryList = null;
            List<ProductRepertoryHistory> repertoryHistoryList = null;
            if (productModel.Id == 0)
            {
                //商品库存 
                if (dormitoryIDs != "")
                {
                    repertoryList = new List<ProductRepertory>();
                    repertoryHistoryList = new List<ProductRepertoryHistory>();
                    var dormitoryidArray = dormitoryIDs.Split(',');
                    foreach (var item in dormitoryidArray)
                    {
                        string counstr = Request.Form["dormitory" + item].ToString();
                        int count = counstr == "" ? 0 : int.Parse(counstr);
                        var repertory = new ProductRepertory()
                        {
                            DormitoryId = int.Parse(item),
                            CollegeId = 1,
                            Remain = count
                        };
                        repertoryList.Add(repertory);

                        var repertoryHistory = new ProductRepertoryHistory()
                        {
                            DormitoryId = int.Parse(item),
                            CollegeId = 1,
                            ProductName = productModel.ProductName,
                            PutDate = DateTime.Now,
                            PutNum = count,
                            UserName = username
                        };
                        repertoryHistoryList.Add(repertoryHistory);

                    }
                }
            }


            var isSuccess = ProductBiz.SaveProduct(product, policy, repertoryList, repertoryHistoryList);
            int opId = -1;
            if (!isSuccess)
            {
                opId = -2;
            }

            return Redirect("/WorkSpace/CollegeAdmin/GeneralProductsDetail/" + opId);
        }
        public ActionResult ProductsImport()
        {
            return View();
        }
        [HttpPost]
        public ActionResult ProductsImport(HttpPostedFile bulk)
        {
            var file = HttpContext.Request.Files;
            if (file != null && file.Count > 0 &&
                file[0].ContentLength > 0 && file[0].FileName.EndsWith(".xls"))
            {
                string path = Server.MapPath("/content/file/temp/" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
                file[0].SaveAs(path);
                ViewBag.Count = ProductBiz.ProductImport(path);
                ViewBag.Success = true;
            }
            else
            {
                ViewBag.Success = false;
            }
            return View();
        }
        public ActionResult DeleteProduct(int id = 0, string productkey = "", int page = 0, int categoryId = 0, int subcategoryId = 0)
        {
            ViewBag.isSuccess = ProductBiz.DelProduct(id);
            return Redirect("/WorkSpace/CollegeAdmin/GeneralProducts?productkey=" + productkey + "&page=" + page + "&categoryId=" + categoryId + "&subcategoryId" + subcategoryId);
        }

        public ActionResult ProductRepertoryDetail(int id = 0, int type = 0, int areacode = 1, string productkey="")
        {
            //商品楼栋
            ViewBag.ProductID = id;
            ViewBag.Type = type;
            ViewBag.AreaCode = areacode;
            ViewBag.Dormitorys = SupportBiz.GetDormitories();
            ViewBag.productRepertorys = new ProductRepertory().FindAll(c => c.ProductId == id);
            ViewBag.SearchKey = productkey;
            return View();
        }
        [HttpPost]
        public ActionResult SetProductRepertory(int id = 0, int type = 0, string dormitoryIDs = "", int areacode = 1, int page = 0, string productkey="")
        {
            var username = System.Web.HttpContext.Current.User.Identity.Name;
            var product = new Product().Find(id.ToString());
            //处理库存
            List<ProductRepertory> repertoryList = null;
            List<ProductRepertoryHistory> repertoryHistoryList = null;
            if (dormitoryIDs != "")
            {
                repertoryList = new List<ProductRepertory>();
                repertoryHistoryList = new List<ProductRepertoryHistory>();
                var dormitoryidArray = dormitoryIDs.Split(',');
                foreach (var item in dormitoryidArray)
                {
                    
                    string newcounstr = Request.Form["newremain" + item].ToString();
                    if (newcounstr != "")
                    {
                        int dormitoryid = int.Parse(item);
                        int newcount = newcounstr == "" ? 0 : int.Parse(newcounstr);
                        var repertoryHistory = new ProductRepertoryHistory()
                        {
                            DormitoryId = dormitoryid,
                            CollegeId = 1,
                            ProductName = product.ProductName,
                            PutDate = DateTime.Now,
                            PutNum = newcount,
                            UserName = username
                        };
                        repertoryHistory.PostAdd();

                        

                        var repertory = new ProductRepertory().Find(c => c.DormitoryId == dormitoryid && c.ProductId == id);
                        if (repertory != null)
                        {
                            repertory.Remain = repertory.Remain + newcount;
                            repertory.PostModify();
                        }
                        else
                        {
                            repertory = new ProductRepertory()
                            {
                                DormitoryId = int.Parse(item),
                                CollegeId = 1,
                                Remain = newcount
                            };
                            repertoryList.Add(repertory);
                        }
                    }
                }
            }
            if (areacode == 1)//普通商品区
            {
                if (type == 0)
                {
                    return Redirect("/WorkSpace/CollegeAdmin/GeneralProducts");
                }
                else
                {
                    return Redirect("/WorkSpace/CollegeAdmin/GeneralProductsDetail/" + id);
                }
            }
            else if(areacode == 3)//积分兑换区
            {
                if (type == 0)
                {
                    return Redirect("/WorkSpace/CollegeAdmin/ExchangeProducts");
                }
                else
                {
                    return Redirect("/WorkSpace/CollegeAdmin/ExchangeProductsDetail/" + id);
                }
            }
            else if (areacode == 2)//团购区
            {
                if (type == 0)
                {
                    return Redirect("/WorkSpace/CollegeAdmin/GroupBuyProducts");
                }
                else
                {
                    return Redirect("/WorkSpace/CollegeAdmin/GroupBuyProductsDetail/" + id);
                }
            }
            else if (areacode == 4)
            {
                if (type == 0)
                {
                    ViewBag.SearchKey = productkey;
                    return Redirect("/WorkSpace/CollegeAdmin/GeneralPackagesProducts?page=" + page + "&productkey=" + productkey);
                }
                else
                {
                    return Redirect("/WorkSpace/CollegeAdmin/GeneralPackagesProductsDetail/" + id);
                }
            }
            return Redirect("/WorkSpace/CollegeAdmin/GeneralProducts");
        }
        #endregion

        #region 积分兑换
        public ActionResult ExchangeProducts(string productkey = "", int page = 0, int categoryId = 0, int subcategoryId = 0)
        {
            //商品分类
            ItemListBox<ProductCategory> categorys = ProductCategoryBiz.GetAllProductCategory();
            List<Object> objList = null;
            if (categorys != null && categorys.Data != null && categorys.Data.Any())
            {
                objList = new List<object>();
                List<object> subList = new List<object>();
                subList.Add(new { value = 0, name = "请选择" });
                objList.Add(new { value = 0, name = "请选择", children = subList });
                foreach (var item in categorys.Data)
                {
                    subList = null;
                    if (item.productCategorys != null && item.productCategorys.Any())
                    {
                        subList = new List<object>();
                        subList.Add(new { value = 0, name = "请选择" });
                        foreach (var subItem in item.productCategorys)
                        {
                            subList.Add(new { value = subItem.Id, name = subItem.CategoryName });
                        }
                    }
                    if (subList != null)
                    {
                        objList.Add(new { value = item.Id, name = item.CategoryName, children = subList });
                    }
                    else
                    {
                        subList = new List<object>();
                        subList.Add(new { value = 0, name = "请选择" });
                        objList.Add(new { value = item.Id, name = item.CategoryName, children = subList });
                    }
                }
            }
            ViewBag.CategorysList = objList.ToJson();
            ViewBag.Data = ProductBiz.GetAllProductsByType(productkey, 3, categoryId, subcategoryId, page, 10);
            ViewBag.SearchKey = productkey;
            ViewBag.CategoryID = categoryId;
            ViewBag.SubCategoryID = subcategoryId;
            return View();
        }

        [HttpPost]
        public ActionResult SearchExchangeProducts(string productKey = "", int productType = 0, int productSubType = 0)
        {
            return Redirect("/WorkSpace/CollegeAdmin/GeneralProducts?productkey=" + productKey + "&categoryId=" + productType + "&subcategoryId=" + productSubType);
        }

        public ActionResult ExchangeProductsDetail(int id = 0)
        {
            //商品楼栋
            ViewBag.Dormitorys = SupportBiz.GetDormitories();
            ItemListBox<ProductCategory> categorys = ProductCategoryBiz.GetAllProductCategory();
            //商品分类
            List<Object> objList = null;
            if (categorys != null && categorys.Data != null && categorys.Data.Any())
            {
                objList = new List<object>();
                foreach (var item in categorys.Data)
                {
                    List<object> subList = null;
                    if (item.productCategorys != null && item.productCategorys.Any())
                    {
                        subList = new List<object>();
                        foreach (var subItem in item.productCategorys)
                        {
                            subList.Add(new { value = subItem.Id, name = subItem.CategoryName });
                        }
                    }
                    if (subList != null)
                    {
                        objList.Add(new { value = item.Id, name = item.CategoryName, children = subList });
                    }
                    else
                    {
                        objList.Add(new { value = item.Id, name = item.CategoryName });
                    }
                }
            }

            ViewBag.CategorysList = objList.ToJson();
            //消息
            if (id == -1)
            {
                ViewBag.isSuccess = true;
            }
            else if (id == -2)
            {
                ViewBag.isSuccess = false;
            }
            //编辑时获取商品信息
            if (id > 0)
            {
                ViewBag.productiId = id; 
                ViewBag.product = new Product().Find(id.ToString());
                var policy = new Policy().Find(c => c.ProductId == id && c.PolicyType == 1);
                policy.Integral = Convert.ToInt32(Math.Round(policy.Price * SupportBiz.GetCostRank(), 0)); 
                ViewBag.policy = policy;
                ViewBag.productRepertorys = new ProductRepertory().FindAll(c => c.ProductId == id);//ProductRepertoryBiz.GetProductRepertoryByProductId(id);
            }
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SaveExchangeProducts(ProductModel productModel, string dormitoryIDs)
        {
            var username = System.Web.HttpContext.Current.User.Identity.Name;
            
            //商品信息
            var product = new Product()
            {
                AreaCode = AreaCode.Integration,
                BusinessId = 0,
                CapsPeople = 0,
                Catering = "",
                CreateDate = DateTime.Now,
                Description = productModel.Description,
                Id = productModel.Id,
                Images = productModel.Images,
                ProductCode = productModel.ProductCode,
                ProductName = productModel.ProductName,
                ProductSubType = productModel.ProductSubType,
                ProductType = productModel.ProductType,
                PurchasePrice = productModel.PurchasePrice,
                OriginalPrice = 0,
                Value = 5
            };
            //处理产品规格
            string versionStr = "";
            if (productModel.VerName != null && productModel.VerName.Length > 0)
            {
                for (int i = 0; i < productModel.VerName.Length; i++)
                {
                    if (productModel.VerName[i] != "" && productModel.VerValue[i] != "")
                    {
                        versionStr = versionStr + productModel.VerName[i] + "#" + (productModel.VerValue[i] == "" ? productModel.VerName[i] : productModel.VerValue[i]) + ";";
                    }
                }
            }
            if (versionStr != "" && versionStr.Length > 0)
            {
                versionStr = versionStr.Substring(0, versionStr.Length - 1);
            }
            product.Version = versionStr;
            //商品价格策略信息
            var policy = new Policy()
            {
                Id = productModel.PolicyId,
                CreateDate = DateTime.Now,
                Creator = username,
                PolicyType = 1,
                Price = productModel.SalePrice /SupportBiz.GetCostRank(),
                ProductName = productModel.ProductName,
                StartDate = DateTime.Now,
                ExpireDate = DateTime.Now,
                IsActive = true
            };
            List<ProductRepertory> repertoryList = null;
            List<ProductRepertoryHistory> repertoryHistoryList = null;
            if (productModel.Id == 0)
            {
                //商品库存 
                if (dormitoryIDs != "")
                {
                    repertoryList = new List<ProductRepertory>();
                    repertoryHistoryList = new List<ProductRepertoryHistory>();
                    var dormitoryidArray = dormitoryIDs.Split(',');
                    foreach (var item in dormitoryidArray)
                    {
                        string counstr = Request.Form["dormitory" + item].ToString();
                        int count = counstr == "" ? 0 : int.Parse(counstr);
                        var repertory = new ProductRepertory()
                        {
                            DormitoryId = int.Parse(item),
                            CollegeId = 1,
                            Remain = count
                        };
                        repertoryList.Add(repertory);

                        var repertoryHistory = new ProductRepertoryHistory()
                        {
                            DormitoryId = int.Parse(item),
                            CollegeId = 1,
                            ProductName = productModel.ProductName,
                            PutDate = DateTime.Now,
                            PutNum = count,
                            UserName = username
                        };
                        repertoryHistoryList.Add(repertoryHistory);

                    }
                }
            }


            var isSuccess = ProductBiz.SaveProduct(product, policy, repertoryList, repertoryHistoryList);
            int opId = -1;
            if (!isSuccess)
            {
                opId = -2;
            }

            return Redirect("/WorkSpace/CollegeAdmin/GeneralProductsDetail/" + opId);
        }

        public ActionResult DeleteExchangeProduct(int id = 0, string productkey = "", int page = 0, int categoryId = 0, int subcategoryId = 0)
        {
            ViewBag.isSuccess = ProductBiz.DelProduct(id);
            return Redirect("/WorkSpace/CollegeAdmin/ExchangeProducts?productkey=" + productkey + "&page=" + page + "&categoryId=" + categoryId + "&subcategoryId" + subcategoryId);
        }
        #endregion

        #region 限时特卖
        public ActionResult ProductSpecialSale(string productkey = "", int page = 0)
        {
            ViewBag.Data = SpecialSaleBiz.GetAllSpecialProducts(productkey, page, 10);
            ViewBag.SearchKey = productkey;
            return View();
        }
        [HttpPost]
        public ActionResult SearchSpecialSaleProducts(string productKey = "")
        {
            return Redirect("/WorkSpace/CollegeAdmin/ProductSpecialSale?productkey=" + productKey);
        }
        public ActionResult ProductSpecialSaleDetail(int productId = 0,int type=0)
        {
            var product = new Product().Find(productId.ToString());
            if (product != null && product.Images != null && product.Images!="")
            {
                product.Images = product.Images.Split(';')[0];
            }
            var policys = new Policy().FindAll(c => c.ProductId == productId);

            ViewBag.Product = product;
            ViewBag.Policys = policys;
            ViewBag.Type = type;
            ViewBag.ProductID = productId;

            return View();
        }
        [HttpPost]
        public ActionResult SaveSpecialSale(DateTime startdate,DateTime enddate, int productId = 0, int type = 0,decimal specialprice=0)
        {
            var username = System.Web.HttpContext.Current.User.Identity.Name;
           // var user = new User().Find(username);
            var product = new Product().Find(productId.ToString());
            var policy = new Policy()
            {
                CreateDate=DateTime.Now,
                Creator = username,//user.RealName,
                ExpireDate=enddate,
                IsActive=true,
                PolicyType=2,
                Price=specialprice,
                ProductId=product.Id,
                ProductName=product.ProductName,
                StartDate=startdate
            };

            SpecialSale specialSale = new SpecialSale()
            {
                CreateDate = DateTime.Now,
                Creator = username,//user.RealName,
                ProductId = product.Id,
                ProductName = product.ProductName
            };

            SpecialSaleBiz.SaveSpecialSale(specialSale, policy);

            return Redirect("/WorkSpace/CollegeAdmin/ProductSpecialSaleDetail?productId=" + productId + "&type=" + type);
            
           
        }

        public ActionResult DeleteSpecailSale(int Id = 0, string productkey = "",int page=0)
        {
            try
            {
                var specailsale = new SpecialSale().Find(c => c.ProductId == Id);
                specailsale.PostDelete();

                var policyList = new Policy().FindAll(c => c.ProductId == Id && c.IsActive == true);
                foreach (var item in policyList)
                {
                    var policy = new Policy().Find(item.Id.ToString());
                    policy.IsActive = false;
                    policy.PostModify();
                }
            }
            catch (Exception ex)
            {
                
                
            }

            return Redirect("/WorkSpace/CollegeAdmin/ProductSpecialSale?ProductSpecialSale=" + productkey + "&page=" + page);
        }

        public ActionResult ModifySpecailSale(int productid,int Id = 0, int type = 0,int state=0)
        {
            var policy = new Policy().Find(Id.ToString());
            policy.IsActive = state==0?false:true;
            policy.PostModify();
            return Redirect("/WorkSpace/CollegeAdmin/ProductSpecialSaleDetail?productId=" + productid + "&type=" + type);
        }
        #endregion

        #region 特别推荐

        public ActionResult RecommendedProducts(string productkey = "", int page = 0)
        {
            ViewBag.SearchKey = productkey;
            ViewBag.data = RecommendedBiz.GetAllRecommendedProducts(productkey, page, 10);
            return View();
        }
        [HttpPost]
        public ActionResult SearchRecommendedProducts(string productKey = "")
        {
            return Redirect("/WorkSpace/CollegeAdmin/RecommendedProducts?productkey=" + productKey);
        }
        public ActionResult SaveRecommended(int productId = 0)
        {
            var product = new Product().Find(productId.ToString());
            var username = System.Web.HttpContext.Current.User.Identity.Name;
            Recommended recommended = new Recommended()
            {
                CreateDate = DateTime.Now,
                Creator = username,//username
                ProductId = product.Id,
                ProductName = product.ProductName
            };
            recommended.PostAdd();
            return Redirect("/WorkSpace/CollegeAdmin/RecommendedProducts");
        }
        public ActionResult DelRecommended(int productId = 0, string productKey="",int page=0)
        {
            var product = new Product().Find(productId.ToString());
            var recommended = new Recommended().Find(c => c.ProductId == productId);
            if (recommended != null)
            {
                recommended.PostDelete();
            }

            return Redirect("/WorkSpace/CollegeAdmin/RecommendedProducts?productkey=" + productKey + "&page=" + page);
        }
        #endregion

        #region 团购商品
        public ActionResult GroupBuyProducts(string productkey = "", int page = 0, int categoryId = 0, int subcategoryId = 0)
        {
            //商品分类
            ItemListBox<ProductCategory> categorys = ProductCategoryBiz.GetAllProductCategory();
            List<Object> objList = null;
            if (categorys != null && categorys.Data != null && categorys.Data.Any())
            {
                objList = new List<object>();
                List<object> subList = new List<object>();
                subList.Add(new { value = 0, name = "请选择" });
                objList.Add(new { value = 0, name = "请选择", children = subList });
                foreach (var item in categorys.Data)
                {
                    subList = null;
                    if (item.productCategorys != null && item.productCategorys.Any())
                    {
                        subList = new List<object>();
                        subList.Add(new { value = 0, name = "请选择" });
                        foreach (var subItem in item.productCategorys)
                        {
                            subList.Add(new { value = subItem.Id, name = subItem.CategoryName });
                        }
                    }
                    if (subList != null)
                    {
                        objList.Add(new { value = item.Id, name = item.CategoryName, children = subList });
                    }
                    else
                    {
                        subList = new List<object>();
                        subList.Add(new { value = 0, name = "请选择" });
                        objList.Add(new { value = item.Id, name = item.CategoryName, children = subList });
                    }
                }
            }
            ViewBag.CategorysList = objList.ToJson();
            ViewBag.Data = GroupBuyProductBiz.GetGroupBuyProducts(productkey, 2, categoryId, subcategoryId, page, 10);
            ViewBag.SearchKey = productkey;
            ViewBag.CategoryID = categoryId;
            ViewBag.SubCategoryID = subcategoryId;
            return View();
        }

        [HttpPost]
        public ActionResult SearchGroupBuyProducts(string productKey = "", int productType = 0, int productSubType = 0)
        {
            return Redirect("/WorkSpace/CollegeAdmin/GeneralProducts?productkey=" + productKey + "&categoryId=" + productType + "&subcategoryId=" + productSubType);
        }

        public ActionResult GroupBuyProductsDetail(int id = 0)
        {
            //商品楼栋
            ViewBag.Dormitorys = SupportBiz.GetDormitories();
            ItemListBox<ProductCategory> categorys = ProductCategoryBiz.GetAllProductCategory();
            //商品分类
            List<Object> objList = null;
            if (categorys != null && categorys.Data != null && categorys.Data.Any())
            {
                objList = new List<object>();
                foreach (var item in categorys.Data)
                {
                    List<object> subList = null;
                    if (item.productCategorys != null && item.productCategorys.Any())
                    {
                        subList = new List<object>();
                        foreach (var subItem in item.productCategorys)
                        {
                            subList.Add(new { value = subItem.Id, name = subItem.CategoryName });
                        }
                    }
                    if (subList != null)
                    {
                        objList.Add(new { value = item.Id, name = item.CategoryName, children = subList });
                    }
                    else
                    {
                        objList.Add(new { value = item.Id, name = item.CategoryName });
                    }
                }
            }

            ViewBag.CategorysList = objList.ToJson();
            //消息
            if (id == -1)
            {
                ViewBag.isSuccess = true;
            }
            else if (id == -2)
            {
                ViewBag.isSuccess = false;
            }
            //编辑时获取商品信息
            if (id > 0)
            {
                ViewBag.productiId = id;
                ViewBag.product = new Product().Find(id.ToString());
                ViewBag.policy = new Policy().Find(c => c.ProductId == id && c.PolicyType == 1);
                ViewBag.productRepertorys = new ProductRepertory().FindAll(c => c.ProductId == id);//ProductRepertoryBiz.GetProductRepertoryByProductId(id);
            }
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SaveGrouBuyProducts(ProductModel productModel, string dormitoryIDs)
        {
            var username = System.Web.HttpContext.Current.User.Identity.Name;
            
            //商品信息
            var product = new Product()
            {
                AreaCode = AreaCode.Group,
                BusinessId = 0,
                CapsPeople = productModel.CapsPeople,
                Catering = "",
                CreateDate = DateTime.Now,
                Description = productModel.Description,
                Id = productModel.Id,
                Images = productModel.Images,
                ProductCode = productModel.ProductCode,
                ProductName = productModel.ProductName,
                ProductSubType = productModel.ProductSubType,
                ProductType = productModel.ProductType,
                PurchasePrice = productModel.PurchasePrice,
                OriginalPrice=productModel.OriginalPrice,
                Value = 5
            };
            //处理产品规格
            string versionStr = "";
            if (productModel.VerName != null && productModel.VerName.Length > 0)
            {
                for (int i = 0; i < productModel.VerName.Length; i++)
                {
                    if (productModel.VerName[i] != "" && productModel.VerValue[i] != "")
                    {
                        versionStr = versionStr + productModel.VerName[i] + "#" + (productModel.VerValue[i] == "" ? productModel.VerName[i] : productModel.VerValue[i]) + ";";
                    }
                }
            }
            if (versionStr != "" && versionStr.Length > 0)
            {
                versionStr = versionStr.Substring(0, versionStr.Length - 1);
            }
            product.Version = versionStr;
            //商品价格策略信息
            var policy = new Policy()
            {
                Id = productModel.PolicyId,
                CreateDate = DateTime.Now,
                Creator = username,// user.RealName,
                PolicyType = 1,
                Price = productModel.SalePrice,
                ProductName = productModel.ProductName,
                StartDate =productModel.StartDate,
                ExpireDate = productModel.ExpireDate,
                IsActive = true
            };
            List<ProductRepertory> repertoryList = null;
            List<ProductRepertoryHistory> repertoryHistoryList = null;
            if (productModel.Id == 0)
            {
                //商品库存 
                if (dormitoryIDs != "")
                {
                    repertoryList = new List<ProductRepertory>();
                    repertoryHistoryList = new List<ProductRepertoryHistory>();
                    var dormitoryidArray = dormitoryIDs.Split(',');
                    foreach (var item in dormitoryidArray)
                    {
                        string counstr = Request.Form["dormitory" + item].ToString();
                        int count = counstr == "" ? 0 : int.Parse(counstr);
                        var repertory = new ProductRepertory()
                        {
                            DormitoryId = int.Parse(item),
                            CollegeId = 1,
                            Remain = count
                        };
                        repertoryList.Add(repertory);

                        var repertoryHistory = new ProductRepertoryHistory()
                        {
                            DormitoryId = int.Parse(item),
                            CollegeId = 1,
                            ProductName = productModel.ProductName,
                            PutDate = DateTime.Now,
                            PutNum = count,
                            UserName = username
                        };
                        repertoryHistoryList.Add(repertoryHistory);

                    }
                }
            }


            var isSuccess = ProductBiz.SaveProduct(product, policy, repertoryList, repertoryHistoryList);
            int opId = -1;
            if (!isSuccess)
            {
                opId = -2;
            }

            return Redirect("/WorkSpace/CollegeAdmin/GroupBuyProductsDetail/" + opId);
        }

        public ActionResult DeleteGrouBuyProduct(int id = 0, string productkey = "", int page = 0, int categoryId = 0, int subcategoryId = 0)
        {
            ViewBag.isSuccess = ProductBiz.DelProduct(id);
            return Redirect("/WorkSpace/CollegeAdmin/GroupBuyProducts?productkey=" + productkey + "&page=" + page + "&categoryId=" + categoryId + "&subcategoryId" + subcategoryId);
        }
        #endregion

        #region 删除商品图片
        public ActionResult DelProductImg(int Id = 0)
        {
            var product = new Product().Find(Id.ToString());
            if (product != null && product.Images != "")
            {
                product.Images = "";
                product.PostModify();
            }
            return Content("");
        }
        #endregion

        #region 商品评价
        public ActionResult ProductAssess(int page = 0)
        {
            List<Object> data = new List<object>();
            ItemListBox<Object> list = new ItemListBox<object>(data).BuildPage(10000, page, 10, new PageParameter() { Style = "workspace" });
            ViewBag.Data = list;
            return View();
        }
        public ActionResult ProductAssessDetail(int productId = 0,int prodcutAssessId=0)
        {
            return View();
        }
        #endregion 

        #region 商品订单
        public ActionResult ProductOrders(int page = 0)
        {
            List<Object> data = new List<object>();
            ItemListBox<Object> list = new ItemListBox<object>(data).BuildPage(10000, page, 10, new PageParameter() { Style = "workspace" });
            ViewBag.Data = list;
            return View();
        }
        #endregion

        #region 快餐相关
        public ActionResult GeneralFastFoods(string productkey = "", int page = 0,int businessId=-1)
        {
            ViewBag.Data = ProductBiz.GetAllProducts(productkey, 10, page, 10, businessId);
            ViewBag.SearchKey = productkey;
            ViewBag.BusinessId = businessId;
            ViewBag.Business = new Business().FindAll();
            return View();
        }
        [HttpPost]
        public ActionResult SearchFastFoods(string productKey = "")
        {
            return Redirect("/WorkSpace/CollegeAdmin/GeneralFastFoods?productkey=" + productKey);
        }


        public ActionResult GeneralFastFoodDetail(int id = 0, int page = 0, string productkey="")
        {
            //消息
            if (id == -1)
            {
                ViewBag.isSuccess = true;
            }
            else if (id == -2)
            {
                ViewBag.isSuccess = false;
            }
            //编辑时获取商品信息
            if (id > 0)
            {
                ViewBag.productiId = id;
                ViewBag.product = new Product().Find(id.ToString());
                ViewBag.policy = new Policy().Find(c => c.ProductId == id && c.PolicyType == 1);
                ViewBag.productRepertorys = new ProductRepertory().FindAll(c => c.ProductId == id);//ProductRepertoryBiz.GetProductRepertoryByProductId(id);
            }
            ViewBag.Page = page;
            ViewBag.productkey = productkey;
            ViewBag.Business = new Business().FindAll();
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SaveGeneralFastFood(ProductModel productModel,int page=0)
        {
            var username = System.Web.HttpContext.Current.User.Identity.Name;
            // var user = new User().Find(username);
            //商品信息
            var product = new Product()
            {
                AreaCode = AreaCode.Snack,
                BusinessId = productModel.BusinessId,
                CapsPeople = 0,
                Catering = "",//配菜字段
                CreateDate = DateTime.Now,
                Description = productModel.Description,
                Id = productModel.Id,
                Images = productModel.Images,
                ProductCode = productModel.ProductCode,
                ProductName = productModel.ProductName,
                ProductSubType = 0,
                ProductType = 0,
                PurchasePrice = 0.00M,
                OriginalPrice = 0,//销售价格
                Value = 5,
                Recomendedstr = "是"
            };
            //处理配菜信息
            CateringSet cateringSet = new CateringSet();
            if (productModel.VerName != null && productModel.VerName.Length > 0)
            {
                List<Catering> cateringList = new List<Catering>();
                string[] verValueArray = new string[2];
                for (int i = 0; i < productModel.VerName.Length; i++)
                {
                    Catering catering = new Catering();
                    catering.caterCategory = productModel.VerName[i];
                    if (productModel.VerName[i] != "" && productModel.VerValue[i] != "")
                    {
                        List<CateringInfo> cateringInfoList = new List<CateringInfo>();
                        string[] verValueMainArray = productModel.VerValue[i].Split('#');
                        if (verValueMainArray.Length != 0) {
                            for (int j = 0; j < verValueMainArray.Length; j++)
                            {
                                CateringInfo cateringInfo = new CateringInfo();
                                verValueArray = verValueMainArray[j].Split('|');
                                if (verValueArray.Length == 2)
                                {
                                    cateringInfo.caterName = verValueArray[0];
                                    cateringInfo.caterNumber = "0";
                                    cateringInfo.caterPrice = verValueArray[1];
                                }
                                cateringInfoList.Add(cateringInfo);
                            }
                            catering.cateringInfoList = cateringInfoList;
                        }                        
                    }
                    cateringList.Add(catering);
                }
                cateringSet.cateringList = cateringList;
            }
            if (cateringSet.cateringList[0] == null || string.IsNullOrEmpty(cateringSet.cateringList[0].caterCategory))
            {
                product.Catering = "";
            }
            else
                product.Catering = cateringSet.ToJson();
            //商品价格策略信息
            var policy = new Policy()
            {
                Id = productModel.PolicyId,
                CreateDate = DateTime.Now,
                Creator = username,// user.RealName,
                PolicyType = 1,
                Price = productModel.SalePrice,
                ProductName = productModel.ProductName,
                StartDate = DateTime.Now,
                ExpireDate = DateTime.Now,
                IsActive = true
            };
            
            var isSuccess = ProductBiz.SaveProduct(product, policy, null, null);
            if (productModel.Id != 0) {
                return Redirect("/WorkSpace/CollegeAdmin/GeneralFastFoods?page=" + page);
            }
            int opId = -1;
            if (!isSuccess)
            {
                opId = -2;
            }

            return Redirect("/WorkSpace/CollegeAdmin/GeneralFastFoodDetail/" + opId);
        }

        public ActionResult DeleteFastFood(int id = 0, string productkey = "", int page = 0)
        {
            ViewBag.isSuccess = ProductBiz.DelProduct(id);

            ViewBag.SearchKey = productkey;
            return Redirect("/WorkSpace/CollegeAdmin/GeneralFastFoods?productkey=" + productkey + "&page=" + page );
        }
        #endregion

        #region 套餐相关
        public ActionResult GeneralPackagesProducts(string productkey = "", int page = 0)
        {
            ViewBag.Data = ProductBiz.GetAllProductsByPackages(productkey, 4, page, 10);
            ViewBag.SearchKey = productkey;
            ViewBag.Business = new Business().FindAll();
            return View();
        }
        [HttpPost]
        public ActionResult SearchPackagesProducts(string productKey = "")
        {
            return Redirect("/WorkSpace/CollegeAdmin/GeneralPackagesProducts?productkey=" + productKey);
        }


        public ActionResult GeneralPackagesProductsDetail(int id = 0, int page = 0, string productkey = "")
        {
            //商品楼栋
            ViewBag.Dormitorys = SupportBiz.GetDormitories();
            ViewBag.productkey = productkey;

            //消息
            if (id == -1)
            {
                ViewBag.isSuccess = true;
            }
            else if (id == -2)
            {
                ViewBag.isSuccess = false;
            }
            //编辑时获取商品信息
            if (id > 0)
            {
                ViewBag.productiId = id;
                ViewBag.product = new Product().Find(id.ToString());
                ViewBag.policy = new Policy().Find(c => c.ProductId == id && c.PolicyType == 1);
                ViewBag.productRepertorys = new ProductRepertory().FindAll(c => c.ProductId == id);//ProductRepertoryBiz.GetProductRepertoryByProductId(id);
            }
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SaveGeneralPackagesProducts(ProductModel productModel, string dormitoryIDs, int page = 0, string productkey = "")
        {
            var username = System.Web.HttpContext.Current.User.Identity.Name;
            
            // var user = new User().Find(username);
            //商品信息
            var product = new Product()
            {
                AreaCode = AreaCode.Combination,
                BusinessId = 0,
                CapsPeople = 0,
                Catering = "",
                CreateDate = DateTime.Now,
                Description = productModel.Description,
                Id = productModel.Id,
                Images = productModel.Images,
                ProductCode = productModel.ProductCode,
                ProductName = productModel.ProductName,
                ProductSubType = 0,
                ProductType = 0,
                PurchasePrice = productModel.PurchasePrice,
                OriginalPrice = 0,
                Recomendedstr = "是",
                Value = 5
            };
            //处理产品规格
            string versionStr = "";
            if (productModel.VerName != null && productModel.VerName.Length > 0)
            {
                for (int i = 0; i < productModel.VerName.Length; i++)
                {
                    if (productModel.VerName[i] != "" && productModel.VerValue[i] != "")
                    {
                        versionStr = versionStr + productModel.VerName[i] + "#" + (productModel.VerValue[i] == "" ? productModel.VerName[i] : productModel.VerValue[i]) + ";";
                    }
                }
            }
            if (versionStr != "" && versionStr.Length > 0)
            {
                versionStr = versionStr.Substring(0, versionStr.Length - 1);
            }
            product.Version = versionStr;

            //商品价格策略信息
            var policy = new Policy()
            {
                Id = productModel.PolicyId,
                CreateDate = DateTime.Now,
                Creator = username,// user.RealName,
                PolicyType = 1,
                Price = productModel.SalePrice,
                ProductName = productModel.ProductName,
                StartDate = DateTime.Now,
                ExpireDate = DateTime.Now,
                IsActive = true
            };

            List<ProductRepertory> repertoryList = null;
            List<ProductRepertoryHistory> repertoryHistoryList = null;
            if (productModel.Id == 0)
            {
                //商品库存 
                if (dormitoryIDs != "")
                {
                    repertoryList = new List<ProductRepertory>();
                    repertoryHistoryList = new List<ProductRepertoryHistory>();
                    var dormitoryidArray = dormitoryIDs.Split(',');
                    foreach (var item in dormitoryidArray)
                    {
                        string counstr = Request.Form["dormitory" + item].ToString();
                        int count = counstr == "" ? 0 : int.Parse(counstr);
                        var repertory = new ProductRepertory()
                        {
                            DormitoryId = int.Parse(item),
                            CollegeId = 1,
                            Remain = count
                        };
                        repertoryList.Add(repertory);

                        var repertoryHistory = new ProductRepertoryHistory()
                        {
                            DormitoryId = int.Parse(item),
                            CollegeId = 1,
                            ProductName = productModel.ProductName,
                            PutDate = DateTime.Now,
                            PutNum = count,
                            UserName = username
                        };
                        repertoryHistoryList.Add(repertoryHistory);

                    }
                }
            }

            var isSuccess = ProductBiz.SaveProduct(product, policy, repertoryList, repertoryHistoryList);
            if (productModel.Id != 0)
            {
                ViewBag.productkey = productkey;
                return Redirect("/WorkSpace/CollegeAdmin/GeneralPackagesProducts?page=" + page + "&productkey=" + productkey);
            }
            int opId = -1;
            if (!isSuccess)
            {
                opId = -2;
            }

            return Redirect("/WorkSpace/CollegeAdmin/GeneralPackagesProductsDetail/" + opId);
        }

        public ActionResult DeletePackagesProducts(int id = 0, string productkey = "", int page = 0)
        {
            ViewBag.isSuccess = ProductBiz.DelProduct(id);
            return Redirect("/WorkSpace/CollegeAdmin/GeneralPackagesProducts?productkey=" + productkey + "&page=" + page);
        }
        #endregion

        #region 商户管理
        /// <summary>
        /// 商户列表
        /// </summary>
        /// <returns></returns>
        public ActionResult BusinessInfoList(int page = 0,string search="")
        {
            ViewBag.BusinessList = BusinessBiz.GetAllBusinessByWhere(page, 10, search);
            ViewBag.Search = search;
            return View();
        }

        /// <summary>
        /// 商户新增
        /// </summary>
        /// <returns></returns>
        public ActionResult NewBusiness()
        {
            return View();
        }
        [HttpPost]
        public ActionResult NewBusiness(BusinessModel model)
        {
            var business = new Business()
            {
                CreateDate = DateTime.Now,
                ContactInfo = model.ContactInfo,
                Creator = HttpContext.User.Identity.Name,
                Name = model.Name,
                Logo = model.Logo,
                SpecialFood = model.SpecialFood,
                MainSell = model.MainSell,
                Address = model.Address,
                ContactPeople=model.ContactPeople
            };

            if (model.StartTime.Length != 0) {
                for (int i = 0; i < model.StartTime.Length; i++)
                {
                    business.DeliveryTime += model.StartTime[i] + "|";
                    business.DeliveryTimeEnd += model.EndTime[i] + "|";
                }
                business.DeliveryTime = business.DeliveryTime.Substring(0, business.DeliveryTime.Length - 1);
                business.DeliveryTimeEnd = business.DeliveryTimeEnd.Substring(0, business.DeliveryTimeEnd.Length - 1);
            }
            if (business.PostAdd() == null)
            {
                LogHelper.Write(CommonLogger.UserSystem, LogLevel.Error, String.Format("校级管理员：{0}添加商户。数据为：{1}",
                   business.Name, business.ToJson()));
                ViewBag.Error = "添加商户信息失败！";
            }
            ViewBag.Error = "";
            return View();
        }

        /// <summary>
        /// 商户修改
        /// </summary>
        /// <returns></returns>
        public ActionResult ModifyBusiness(int d, int page = 0)
        {
            ViewBag.page = page;
            ViewBag.BusinessModel = new Business().Find(d.ToString());
            return View();
        }
        [HttpPost]
        public ActionResult ModifyBusiness(BusinessModel model, int page)
        {
            var business = new Business().Find(model.Id.ToString());

            if (business != null)
            {
                business.ContactInfo = model.ContactInfo;
                business.Logo = model.Logo;
                business.DeliveryTime = model.DeliveryTime;
                business.SpecialFood = model.SpecialFood;
                business.MainSell = model.MainSell;
                business.Address = model.Address;
                business.DeliveryTime = "";
                business.DeliveryTimeEnd = "";
                business.ContactPeople = model.ContactPeople;
                if (model.StartTime.Length != 0)
                {
                    for (int i = 0; i < model.StartTime.Length; i++)
                    {
                        business.DeliveryTime += model.StartTime[i] + "|";
                        business.DeliveryTimeEnd += model.EndTime[i] + "|";
                    }
                    business.DeliveryTime = business.DeliveryTime.Substring(0, business.DeliveryTime.Length - 1);
                    business.DeliveryTimeEnd = business.DeliveryTimeEnd.Substring(0, business.DeliveryTimeEnd.Length - 1);
                }

                if (business.PostModify() == null)
                {
                    LogHelper.Write(CommonLogger.UserSystem, LogLevel.Error, String.Format("校级管理员：{0}修改商户。数据为：{1}",
                   business.Name, business.ToJson()));
                    ViewBag.Error = "修改商户信息失败！";
                    return View();
                }
                ViewBag.Error = "";
            }
            return Redirect("/workspace/collegeadmin/BusinessInfoList?page=" + page);
        }

        public bool BusinessNameOnly(string name)
        {
            return BusinessBiz.BusinessNotExists(name);
        }
        /// <summary>
        /// 商户详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult BusinessInfo(int d, int page = 0, int r = 0)
        {
            ViewBag.page = page;
            ViewBag.BusinessModel = new Business().Find(d.ToString());
            return View();
        }

        public ActionResult DelBusiness(int d, int page)
        {
            var business = new Business().Find(d.ToString());

            if (business != null)
            {

                if (business.PostDelete() == null)
                {
                    LogHelper.Write(CommonLogger.UserSystem, LogLevel.Error, String.Format("校级管理员：{0}删除商户。数据为：{1}",
                     business.Name, business.ToJson()));
                    ViewBag.Error = "删除商户信息失败！";
                    return View();
                }
            }
            ViewBag.Error = "";
            return Redirect("/workspace/collegeadmin/BusinessInfoList?page=" + page);

        }

        public void SWFPrepareUpload()
        {
            new UploadTool().SWFPrepareUpload("/content/file/business/");
        }
        #endregion

        #region 楼栋管理

        public ActionResult DormitoryInfoList(int page = 0, string search = "")
        {
            var Dormitorys = DormitoryBiz.GetAllDormitory(page, 10, search);
            ViewBag.Dormitorys = Dormitorys;
            ViewBag.Search = search;
            return View();
        }

        public ActionResult NewDormitory()
        {
            return View();
        }
        [HttpPost]
        public ActionResult NewDormitory(string name)
        {
            if (!DormitoryBiz.IsExits(name))
            {
                ViewBag.Error = "楼栋已存在！";
                return View();
            }
            var dormitory = DormitoryBiz.SaveNewDormitory(1, name, HttpContext.User.Identity.Name);
            int opId = -2;
            if (dormitory != null)
            {
                opId = dormitory.Id;
                ViewBag.Error = "";
            }
            else {
                ViewBag.Error = "操作失败！";
            }
            return View();
        }

        public ActionResult DelDormitory(int id=0,int page=0) {
            page = page < 0 ? 0 : page;
            ViewBag.isSuccess = DormitoryBiz.Delete(id);
            return Redirect("/workspace/collegeadmin/DormitoryInfoList?page=" + page);
        }

        public ActionResult duty(int page=0)
        {
            page = page < 0 ? 0 : page;
            ViewBag.Duty = SupportBiz.GetAllDutySet("", "", page, 3);
            return View();
        }
        [HttpPost]
        public ActionResult duty(string querystart, string queryend,int page=0)
        {
            ViewBag.Duty = SupportBiz.GetAllDutySet(querystart,queryend,page,10);
            return View();
        }
        public ActionResult newdutyset()
        {
            ViewBag.Dormitory = SupportBiz.GetDormitories();//.GetAllDormitoryAndStaff();
            ViewBag.Staff = SupportBiz.GetAllStaff();
            return View();
        }
        [HttpPost]
        public ActionResult newdutyset(string setstart, string setend)
        {
            DateTime start = DateTime.Now;
            DateTime end = DateTime.Now;
            try
            {
                start = DateTime.Parse(setstart);
                end = DateTime.Parse(setend);
                if (end < start)
                {
                    return RedirectToAction("duty");
                }
            }
            catch
            {
                return RedirectToAction("duty");
            }
            List<Dormitory> dormitories = new Dormitory().FindAll();
            if (dormitories != null && dormitories.Any())
            {
                DutySet contract = new DutySet();
                contract.duty = new List<DormitoryDuty>();
                foreach (var item in dormitories)
                {
                    DormitoryDuty duty = new DormitoryDuty();
                    duty.Dormitory = item.Id;
                    duty.userList = new DayDuty();
                    string first = Request.Form["first" + item.Id];
                    if (!String.IsNullOrEmpty(first) && first.Split('|').Length == 2)
                    {
                        duty.userList.first = new DutyUser();
                        duty.userList.first.Username = first.Split('|')[0];
                        duty.userList.first.Realname = first.Split('|')[1];
                    }
                    string middle = Request.Form["middle" + item.Id];
                    if (!String.IsNullOrEmpty(middle) && middle.Split('|').Length == 2)
                    {
                        duty.userList.middle = new DutyUser();
                        duty.userList.middle.Username = middle.Split('|')[0];
                        duty.userList.middle.Realname = middle.Split('|')[1];
                    }
                    string last = Request.Form["last" + item.Id];
                    if (!String.IsNullOrEmpty(last) && last.Split('|').Length == 2)
                    {
                        duty.userList.last = new DutyUser();
                        duty.userList.last.Username = last.Split('|')[0];
                        duty.userList.last.Realname = last.Split('|')[1];
                    }
                    contract.duty.Add(duty);
                }
                for (int i = 0, len = end.Subtract(start).Days; i <= len; i++)
                {
                    if (start.AddDays(i) < DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd")))
                    {
                        continue;
                    }
                    SupportBiz.SetDuty(contract, start.AddDays(i).ToString("yyyy-MM-dd"));
                }
                return RedirectToAction("duty");
                
            }
            return View();
        }

        public bool IsExits(string name)
        {
            return DormitoryBiz.IsExits(name);
        }
        #endregion

        #region 用户
        /// <summary>
        /// 用户列表
        /// </summary>
        /// <returns></returns>
        public ActionResult UserInfoList(UserModel model,int page = 0)
        {
            ViewBag.UserList = UserBiz.GetAllUserByWhere(page, 10, model.SystemRole, model.FloorId, model.Gender, -1, model.Dormitory, model.NickName, model.RealName);
            ViewBag.DormitoryList = new Dormitory().FindAll();
            ViewBag.SearchModel = model;
            return View();
        }

        

        /// <summary>
        /// 用户新增
        /// </summary>
        /// <returns></returns>
        public ActionResult NewUser()
        {
            ViewBag.DormitoryList = new Dormitory().FindAll();
            return View();
        }
        private string userNameEnd = "@xiao-life.com";
        [HttpPost]
        public ActionResult NewUser(UserModel model)
        {
            var user = new User()
            {
                Birthday = DateTime.Now,
                CollegeId = model.CollegeId,
                CreateDate = DateTime.Now,
                Gender = model.Gender == 1 ? Gender.Male : Gender.Female,
                IdCardNo = model.IdCardNo,
                RealName = model.RealName,
                IsActivate = true,
                IsRefuse = model.IsRefuse == 1 ? true : false,
                NickName = model.NickName,
                Password = model.Password,
                Phone = model.Phone,
                QQ = model.QQ,
                FloorId=model.FloorId,
                Dormitory=model.Dormitory,
                UserName = model.UserName.ToLower()+userNameEnd,
                SystemRole = Infrastructure.Entities.Enum.UserRole.Staff,
                RebateLevel = model.RebateLevel,
                Classes = model.Classes,
                Departments = model.Departments,

            };
            if (UserBiz.Register(user,true) == null)
            {
                LogHelper.Write(CommonLogger.UserSystem, LogLevel.Error, String.Format("校级管理员：{0}注册失败。注册数据为：{1}",
                   user.UserName, user.ToJson()));
                ViewBag.Error = "添加校级管理员信息失败！";
            }
            ViewBag.Error = "";
            ViewBag.DormitoryList = new Dormitory().FindAll();
            return View();
        }

        /// <summary>
        /// 用户修改
        /// </summary>
        /// <returns></returns>
        public ActionResult ModifyUser(string u = "", int page = 0)
        {
            ViewBag.page = page;
            ViewBag.User = new User().Find(u);
            ViewBag.DormitoryList = new Dormitory().FindAll();
            return View();
        }
        [HttpPost]
        public ActionResult ModifyUser(UserModel model, int page)
        {
            var user = new User().Find(model.UserName);

            if (user != null)
            {
                user.Gender = model.Gender == 1 ? Gender.Male : Gender.Female;
                user.IdCardNo = model.IdCardNo;
                user.RealName = model.RealName;
                user.IsRefuse = model.IsRefuse == 1 ? true : false;
                user.NickName = model.NickName;
                user.Phone = model.Phone;
                user.QQ = model.QQ;
                user.Dormitory = model.Dormitory;
                user.FloorId = model.FloorId;
                user.SystemRole = Infrastructure.Entities.Enum.UserRole.Staff;
                user.RebateLevel = model.RebateLevel;
                user.Classes = model.Classes;
                user.Departments = model.Departments;

                if (user.PostModify() == null)
                {
                    LogHelper.Write(CommonLogger.UserSystem, LogLevel.Error, String.Format("校级管理员：{0}注册失败。注册数据为：{1}",
                       user.UserName, user.ToJson()));
                    ViewBag.Error = "修改校级管理员信息失败！";
                    return View();
                }
                ViewBag.Error = "";
            }
            return Redirect("/workspace/collegeadmin/userinfolist?page=" + page);
        }

        public bool UserNameOnly(string UserName)
        {
            return UserBiz.UserNotExists(UserName);
        }
        /// <summary>
        /// 用户详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult UserInfo(string u, int page = 0,int r=0)
        {
            ViewBag.page = page;
            ViewBag.Register = r;
            ViewBag.User = new User().Find(u);
            return View();
        }

        public ActionResult ModifyStatu(string u, int page, int s, int r = 0)
        {
            var user = new User().Find(u);

            if (user != null)
            {
                user.IsRefuse = s == 1 ? true : false;

                if (user.PostModify() != null)
                {
                    if (r == 1)
                    {

                        return Redirect("/workspace/collegeadmin/registeruserinfolist?page=" + page);
                    }
                    else
                        return Redirect("/workspace/collegeadmin/userinfolist?page=" + page);
                }
            }
            if (r == 1)
            {

                return Redirect("/workspace/collegeadmin/registeruserinfolist?page=" + page);
            }
            else
                return Redirect("/workspace/collegeadmin/userinfolist?page=" + page);
        }

        public ActionResult ModifyPassWord(string u, int page)
        {
            ViewBag.page = page;
            ViewBag.userName = u;
            return View();
        }
        [HttpPost]
        public ActionResult ModifyPassWord(string u, int page, string Confirm)
        {
            var user = new User().Find(u);

            if (user != null)
            {
                user.Password = AesAlgorithm.Encrypt(Confirm);

                if (user.PostModify() == null)
                {
                    LogHelper.Write(CommonLogger.UserSystem, LogLevel.Error, String.Format("校级管理员：{0}注册失败。注册数据为：{1}",
                       user.UserName, user.ToJson()));
                    ViewBag.Error = "修改校级管理员密码失败！";
                    return View();
                }
            }
            ViewBag.Error = "";
            return Redirect("/workspace/collegeadmin/userinfolist?page=" + page);
        }

        public ActionResult DelUser(string u, int page)
        {
            var user = new User().Find(u);

            if (user != null)
            {

                if (user.PostDelete() == null)
                {
                    LogHelper.Write(CommonLogger.UserSystem, LogLevel.Error, String.Format("校级管理员：{0}注册失败。注册数据为：{1}",
                       user.UserName, user.ToJson()));
                    ViewBag.Error = "删除校级管理员信息失败！";
                    return View();
                }
            }
            ViewBag.Error = "";
            return Redirect("/workspace/collegeadmin/userinfolist?page=" + page);

        }
        #endregion

        #region 订单统计        
        public ActionResult OrdersStatistics(string realName = "", string dtstart = "", string dtend = "", int status = -1, int page = 0)
        {
            int orderCount = 0;
            decimal totalPrice = 0.00m;
            var orderList = OrderBiz.OrderQuery(UserRole.CollegeAdmin, -1, realName, dtstart, dtend, status,false, page, 10, ref orderCount, ref totalPrice);
            ViewBag.OrderList = orderList;

            #region 回填数据
            ViewBag.realName = realName;
            ViewBag.dtstart = dtstart;
            ViewBag.dtend = dtend;
            ViewBag.status = status;
            ViewBag.orderCount = orderCount;
            ViewBag.totalPrice = totalPrice;
            #endregion

            return View();
        }
        public ActionResult OrderDetail(int id)
        {
            Order order = new Order().Find(id.ToString());
            List<OrderDetail> orderDetailList = new OrderDetail().FindAll(c => c.OrderId == id);
            string name = System.Web.HttpContext.Current.User.Identity.Name;
            var user = new User().Find(name);
            ViewBag.User = user;
            ViewBag.Order = order;
            ViewBag.OrderDetail = orderDetailList;
            ViewBag.OrderHistory = new OrderHistory().FindAll(c => c.OrderId == order.Id);
            return View();
        }
        #endregion


        #region 个人信息
        /// <summary>
        /// 个人信息首页
        /// </summary>
        /// <returns></returns>
        public ActionResult MyInfo()
        {
            string userName = HttpContext.User.Identity.Name;
            ViewBag.UserModel = new User().Find(userName);
            ViewBag.DormitoryList = new Dormitory().FindAll();
            return View();
        }

        /// <summary>
        /// 修改个人信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult MyInfo(UserModel model)
        {
            var user = new User().Find(model.UserName);

            if (user != null)
            {
                user.Gender = model.Gender == 1 ? Gender.Male : Gender.Female;
                user.IdCardNo = model.IdCardNo;
                user.RealName = model.RealName;
                user.NickName = model.NickName;
                user.Phone = model.Phone;
                user.QQ = model.QQ;
                user.Dormitory = model.Dormitory;
                user.FloorId = model.FloorId;

                if (user.PostModify() == null)
                {
                    LogHelper.Write(CommonLogger.UserSystem, LogLevel.Error, String.Format("校级管理员：{0}修改个人信息失败。注册数据为：{1}",
                       user.UserName, user.ToJson()));
                    ViewBag.Error = "修改信息失败！";
                    return View();
                }
                ViewBag.UserModel = user;
                ViewBag.Error = "";
            }
            ViewBag.UserModel = user;
            ViewBag.DormitoryList = new Dormitory().FindAll();
            return View();
        }
        public ActionResult Secret()
        {
            return View();
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="Confirm"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Secret(string Confirm)
        {
            var user = new User().Find(HttpContext.User.Identity.Name);

            if (user != null)
            {
                user.Password = AesAlgorithm.Encrypt(Confirm);

                if (user.PostModify() == null)
                {
                    LogHelper.Write(CommonLogger.UserSystem, LogLevel.Error, String.Format("校级管理员：{0}修改密码失败。注册数据为：{1}",
                       user.UserName, user.ToJson()));
                    ViewBag.Error = "修改密码失败！";
                    return View();
                }
            }
            ViewBag.Error = "";
            return View();
        }
        #endregion
    }
}
